<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Widget
{

    private $_widget = NULL;

    /**
     * CodeIgniter global
     *
     * @var string
     **/
    protected $ci;

    /**
     *
     */
    public function __construct()
    {
        $this->ci =& get_instance();
    }

    private function create_widget_class($widget_name)
    {
        $widget_found = FALSE;
        // search on global widget folder
        $widget_file = APPPATH . 'widgets' . DIRECTORY_SEPARATOR . $widget_name . DIRECTORY_SEPARATOR . $widget_name . EXT;

        $widget_found = file_exists( $widget_file );

        // search on modules folders
        if ($widget_found===FALSE) {
            $this->ci->load->helper('file');
            $dir_items = get_dir_file_info(APPPATH . 'modules' . DIRECTORY_SEPARATOR, TRUE, FALSE);

            $modules = array();
            foreach ($dir_items as $key => $value) {
                $path = $value['relative_path'] . $value['name'];
                $widget_file = $path . DIRECTORY_SEPARATOR . 'widgets' . DIRECTORY_SEPARATOR . $widget_name . EXT;
                $widget_found = file_exists( $widget_file );
                if ($widget_found===TRUE) {
                    break;
                }
            }
        }

        if ($widget_found===TRUE) {
            require_once $widget_file;
            $class_name = ucfirst($widget_name);
            $this->_widget = new $class_name;
        }
        else
        {
            $this->_widget = NULL;
        }
        
        return $widget_found;
    }

    private function load($widget_name)
    {
        return $this->create_widget_class($widget_name);
    }

    public function render()
    {
        
    }

    public function run($widget_name, $options)
    {
        $this->load($widget_name);

        if (isset($this->_widget))
        {
            $this->_widget->render($options);
        }
        else
        {
            echo 'ERROR: Widget (' . $widget_name . ') not found';
        }
    }


}
